package com.aliyun.heiyu.powermaster.server.service;

import com.aliyun.heiyu.common.util.CalendarUtil;
import com.aliyun.heiyu.common.util.DateUtil;
import com.aliyun.heiyu.common.util.HttpUtil;
import com.aliyun.heiyu.common.util.PropertiesUtil;
import com.aliyun.heiyu.common.util.StringUtil;
import com.aliyun.heiyu.common.util.TimeConvertUtil;
import com.aliyun.heiyu.powermaster.proto.*;
import com.aliyun.heiyu.powermaster.server.util.Configuration;
import com.aliyun.heiyu.powermaster.server.dao.EnergyViewProviderDao;
import com.aliyun.heiyu.powermaster.server.dao.impl.EnergyViewProviderDaoImpl;
import com.aliyun.heiyu.powermaster.server.factory.MasterThreadFactory;
import com.aliyun.heiyu.powermaster.server.util.*;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class EnergyViewProviderImpl implements EnergyViewProvider {

    private static Logger logger = LoggerFactory.getLogger(EnergyViewProviderImpl.class);
    private static String ip=Configuration.IP;
    private EnergyViewProviderDao energyViewProviderDao;
    private PowerDataService powerDataService;
    private String url=PropertiesUtil.getValue("serverIp.properties", "businessUrl");
    private int detectionTime = 5;
    private int energyEfficiencyRatioTime = 60;
    private String hour="hour";
    private String day="day";
    private String week="week";
    private String month="month";
    private String  energyIp  =PropertiesUtil.getValue("serverIp.properties", "energyIp");



    public EnergyViewProviderImpl() {
        this.energyViewProviderDao=new EnergyViewProviderDaoImpl();
        this.powerDataService=new PowerDataServiceImpl();
            serverCollect();
            energyEfficiencyRatio();

    }

    //定时周期计算能效比并入库
    void  energyEfficiencyRatio() {
        final Calendar instance = Calendar.getInstance();
        ThreadPoolExecutor executorService = new ThreadPoolExecutor(1, 1,
            60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new MasterThreadFactory("energyEfficiencyRatioCollect"));
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    if(!ZkClientUtil.checkLeader()) {
                        return;
                    }
                    Date date = new Date();
                    instance.setTime(date);
                    //获取当前小时
                    int dayTime=instance.get(Calendar.HOUR_OF_DAY);
                    //判断当前是否为0点或24点
                    //获取当前分钟数
                    int hourTime = instance.get(Calendar.MINUTE);
                    //判断当前分钟为整60分间隔
                    if (hourTime % energyEfficiencyRatioTime == 0) {
                        try {
                            String endTime = DateUtil.getStringDate(date);
                            long endMil = DateUtil.dateToMillisecond(endTime);
                            long t=energyEfficiencyRatioTime*60*1000;
                            long startMil = endMil - t;
                            String startTime=DateUtil.millisecondToDate(startMil);
                            double result = eerCalculation(startTime, endTime);
                            energyViewProviderDao.insertEnergyEfficiencyRatio(result,startTime,endTime,hour);
                            if(dayTime % 24 == 0){
                                long endMilDay = DateUtil.dateToMillisecond(endTime);
                                String end = DateUtil.millisecondToDate(endMilDay - 1);
                                long tDay=24*60*60*1000;
                                long startMilDay = endMilDay - tDay;
                                String startTimeDay=DateUtil.millisecondToDate(startMilDay);
                                Map<String, String> avgEer = energyViewProviderDao.findAvgEer(startTimeDay, end, hour);
                                double resultDay=0;
                                if(avgEer == null || avgEer.size() == 0) {
                                    energyViewProviderDao.insertEnergyEfficiencyRatio(resultDay,startTimeDay,end,day);
                                }else {
                                    resultDay= Double.valueOf(avgEer.get("avg"));
                                    energyViewProviderDao.insertEnergyEfficiencyRatio(resultDay,startTimeDay,end,day);
                                }
                            }

                            if(dayTime % 24 == 0 && 2==CalendarUtil.getDayOfWeek()) {
                                long endMilWeek = DateUtil.dateToMillisecond(endTime);
                                long tWeek=7*24*60*60*1000;
                                long startMilWeek = endMilWeek - tWeek;
                                String startTimeWeek=DateUtil.millisecondToDate(startMilWeek);
                                Map<String, String> avgEer = energyViewProviderDao.findAvgEer(startTimeWeek, DateUtil.millisecondToDate(endMilWeek-1), day);
                                double resultDay=0;
                                if(avgEer==null||avgEer.size()==0){
                                    energyViewProviderDao.insertEnergyEfficiencyRatio(resultDay,startTimeWeek,DateUtil.millisecondToDate(endMilWeek-1),week);
                                }else {
                                    resultDay= Double.valueOf(avgEer.get("avg"));
                                    energyViewProviderDao.insertEnergyEfficiencyRatio(resultDay,startTimeWeek,DateUtil.millisecondToDate(endMilWeek-1),week);
                                }
                            }

                            if(dayTime % 24 == 0 && 1==CalendarUtil.getDayOfMonth()){
                                CalendarUtil calendarUtil=new CalendarUtil();
                                String previousMonthFirst = calendarUtil.getPreviousMonthFirst();
                                long endMonthMil = DateUtil.dateToMillisecond(endTime) - 1;
                                String endMonth = DateUtil.millisecondToDate(endMonthMil);
                                Map<String, String> avgEer = energyViewProviderDao.findAvgEer(previousMonthFirst, endMonth, day);
                                double resultMonth=0;
                                if(avgEer == null || avgEer.size() == 0){
                                    energyViewProviderDao.insertEnergyEfficiencyRatio(resultMonth,previousMonthFirst,endMonth,month);
                                }else {
                                    resultMonth = Double.valueOf(avgEer.get("avg"));
                                    energyViewProviderDao.insertEnergyEfficiencyRatio(resultMonth,previousMonthFirst,endMonth,month);
                                }
                            }
                            Thread.sleep(55 * 60 * 1000);
                        }catch (Exception e){
                            logger.error(e.getMessage(),e);
                            e.printStackTrace();
                        }
                    }

                }
            }
        });

    }

    //定时间隔5分钟查询服务器数量及cpu、gpu型机器数量并入库
    void serverCollect() {
        System.out.println("采集开始");
        final Calendar instance = Calendar.getInstance();
        ThreadPoolExecutor executorService = new ThreadPoolExecutor(1, 1,
            60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new MasterThreadFactory("server-amount"));
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    if(!ZkClientUtil.checkLeader()) {
                        return;
                    }
                    Date date = new Date();
                    instance.setTime(date);
                    //获取当前分钟数
                    //时间5分钟查一次
                    int time = instance.get(Calendar.MINUTE);
                    //判断当前分钟为整5分间隔
                    if (time % 5 == 0) {
                        try {
                            //采集没有关联业务所有服务器数量、cpu机器数量、gpu机器数量并存库
                            Map<String, String> map = energyViewProviderDao.totalServerAmount();
                            //获取总数量
                            int serverTotalAmount = Integer.valueOf(map.get("count"));
                            //获取机型为gpu的所有sn并按逗号切割为数组，数组长度为gpu数量
                            int gpuAmount = 0;
                            Map<String, String> gpuSNs = energyViewProviderDao.findGpuSNs();
                            String[] device_ids = null ;
                            if (gpuSNs != null && gpuSNs.size() != 0) {
                                String device_id = gpuSNs.get("device_id");
                                if (null != device_id && device_id.length() != 0) {
                                    device_ids = device_id.split(",");
                                    gpuAmount = device_ids.length;
                                }
                            }
                            //cpu数量为总数量减去gpu数量
                            int cpuAmount = serverTotalAmount - gpuAmount;
                            //手动添加业务名称all代表所有服务器
                            energyViewProviderDao.insertServerAmount("all",cpuAmount,gpuAmount,serverTotalAmount,date,0);
                            //采集关联业务下所有服务器数量、cpu机器数量、gpu机器数量并存库
                            //获取到所有业务ids并按逗号切割为数组
                            Map<String, String> busMap = energyViewProviderDao.findBusinessIds();
                            if (null != busMap && busMap.size() !=0) {
                                String businessIds = busMap.get("ids");
                                if (!StringUtil.isEmpty(businessIds)) {
                                    String[] businessId = businessIds.split(",");
                                    //遍历数组，通过http调用market业务接口查询业务下所含设备sn
                                    for(int i=0;i<businessId.length;i++){
                                        JSONObject json = HttpUtil.getHttpsRequest(url+businessId[i] + "?token=market_token");
                                        if(null == json){
                                            continue;
                                        }
                                        JSONObject data = json.getJSONObject("data");
                                        JSONObject business = data.getJSONObject("business");
                                        String businessName = business.get("name").toString();
                                        JSONArray businessDeviceInfos = business.getJSONArray("businessDeviceInfos");
                                        if(businessDeviceInfos.length() == 0 || null == businessDeviceInfos){
                                            energyViewProviderDao.insertServerAmount(businessName,0,0,0,date,Integer.valueOf(businessId[i]));
                                            continue;
                                        }
                                        int businessServerTotalAmount= businessDeviceInfos.length();
                                        int businessGpuAmount=0;
                                        for(int j=0;j<businessDeviceInfos.length();j++){
                                            String equipmentNumber = businessDeviceInfos.getJSONObject(j).get("equipmentNumber").toString();
                                            if (null != device_ids && device_ids.length != 0) {
                                                for (String gpuSn :device_ids) {
                                                    if(equipmentNumber.equals(gpuSn)){
                                                        businessGpuAmount++;
                                                    }
                                                }
                                            }
                                        }
                                        int businessCpuAmount=businessServerTotalAmount-businessGpuAmount;
                                        energyViewProviderDao.insertServerAmount(businessName,businessCpuAmount,businessGpuAmount,businessServerTotalAmount,date,Integer.valueOf(businessId[i]));
                                    }
                                }
                            }

                            Thread.sleep(120 * 1000);
                        }catch (Exception e){
                            logger.error(e.getMessage(),e);
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
    }


    @Override
    public GetQpsAndServerAmountReply getQpsAndServerAmount(String business_ids, String startTime, String endTime) {
        GetQpsAndServerAmountReply.Builder builder=GetQpsAndServerAmountReply.newBuilder();
        QpsAndServerAmount.Builder build=QpsAndServerAmount.newBuilder();
        String[] split = business_ids.split(",");
        for (String business_id : split) {
            int id = Integer.valueOf(business_id);
                List<Map<String, String>> serverModelList = energyViewProviderDao.findServerModelAmount(id, startTime, endTime);
            if (null == serverModelList || serverModelList.size() == 0) {
               continue;
            }

            for(int i=0;i<serverModelList.size();i++){
                Map<String, String> map = serverModelList.get(i);
                String collect_time = TimeConvertUtil.mysqlTimeSubstring(map.get("collect_time"));
                build.addServerAmountInfos(ServerAmountInfos.newBuilder().setCpuAmount(Integer.valueOf(map.get("cpu_amount"))).setGpuAmount(Integer.valueOf(map.get("gpu_amount")))
                    .setTotalAmount(Integer.valueOf(map.get("server_amount"))).setCollectTime(collect_time).setBusiness(map.get("business")).build());
            }

            List<Map<String, String>> qpsList= energyViewProviderDao.findQpsByBusiness(id, startTime, endTime);
            if (null == qpsList || qpsList.size() == 0) {
                continue;
            }
            for (int i = 0;i<qpsList.size();i++){
                Map<String, String> map = qpsList.get(i);
                String collectTime = TimeConvertUtil.mysqlTimeSubstring(map.get("collect_time"));
                String throughput = map.get("throughput");
                if (StringUtil.isEmpty(throughput)) {
                    throughput = "0";
                }
                BigDecimal bigDecimal = new BigDecimal(throughput);
                String qps = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).toString();
                build.addQpsInfos(QpsInfos.newBuilder().setQps(qps).setCollectTime(collectTime).setBusiness(map.get("business_name")).build());
            }
        }
        return builder.setData(build).build();
    }

    @Override
    public GetServerPowerAndAirTempReply getServerPowerAndAirTemp(String startTime, String endTime) {
        GetServerPowerAndAirTempReply.Builder builder=GetServerPowerAndAirTempReply.newBuilder();
        ServerPowerAndAirTempData.Builder build=ServerPowerAndAirTempData.newBuilder();
        List<Map<String, String>> airRecommendTempList = energyViewProviderDao.findAirRecommendTemp( startTime, endTime);
        if (null == airRecommendTempList || airRecommendTempList.size() == 0) {
            return builder.build();
        }
        //获取所有服务器历史功耗
        List<PowerByLabel> allServer = powerDataService.getPowerForAi("AllServer", startTime, endTime, 0).getDataList();
        if (null == allServer || allServer.size() == 0) {
            return builder.build();
        }
        //获取所有服务器总功耗列表
        List<PowerInfo> infosList = allServer.get(0).getInfosList();
        for(int i=0;i<infosList.size();i++){
            int sumSerPower = infosList.get(i).getSumSerPower();
            String collect_time = infosList.get(i).getCollectTime();
            build.addServerPowerInfos(ServerPowerInfos.newBuilder().setPower(sumSerPower).setCollectTime(collect_time).build());
        }
        for(int i=0;i<airRecommendTempList.size();i++){
            Map<String, String> map = airRecommendTempList.get(i);
            String time = map.get("collect_time");
            String collect_time = time.substring(0, time.indexOf("."));
            build.addAirTemps(AirTemps.newBuilder().setRecommendTemp(Double.valueOf(map.get("recommend_temp"))).setCollectTime(collect_time).build());
        }
        return builder.setData(build).build();
    }

    @Override
    //获取当前能效比和5分钟能效比
    public GetEnergyEfficiencyRatioInfosReply getEnergyEfficiencyRatioInfos() {
        GetEnergyEfficiencyRatioInfosReply.Builder builder = GetEnergyEfficiencyRatioInfosReply.newBuilder();
        EnergyEfficiencyRatioInfosData.Builder build = EnergyEfficiencyRatioInfosData.newBuilder();
        Date date = new Date();
        String endTime = DateUtil.getStringDate(date);
        long endMil = DateUtil.dateToMillisecond(endTime);
        long t = 60 * 1000;
        long startMil = endMil - t;
        String startTime = DateUtil.millisecondToDate(startMil);
        double result = eerCalculation(startTime, endTime);
        build.setCurrent(result);
        long fiveMin = 5 * 60 * 1000;
        for (int i = 0; i < 6; i++){
            long endMils = endMil - i*fiveMin;
            String endT = DateUtil.millisecondToDate(endMils);
            long start = endMils - fiveMin;
            String startT = DateUtil.millisecondToDate(start);
            double eer = eerCalculation(startT, endT);
            build.addEnergyEfficiencyRatioInfo(EnergyEfficiencyRatioInfo.newBuilder().setEnergyEfficiencyRatio(eer).setStartTime(startT).setEndTime(endT).build());
        }
        return builder.setData(build).build();
    }

    @Override
    public GetEnergyEfficiencyRatioHistoryReply getEnergyEfficiencyRatioHistory(String cycle) {
        GetEnergyEfficiencyRatioHistoryReply.Builder builder = GetEnergyEfficiencyRatioHistoryReply.newBuilder();
        EnergyEfficiencyRatioInfosData.Builder build = EnergyEfficiencyRatioInfosData.newBuilder();
        Date date = new Date();
        String endTime = DateUtil.getStringDate(date);
        CalendarUtil calendarUtil = new CalendarUtil();

        switch (cycle){
            case "hour":
                List<Map<String, String>> energyEfficiencyRatio = energyViewProviderDao.findEnergyEfficiencyRatioByCycle(cycle);
                if (energyEfficiencyRatio == null || energyEfficiencyRatio.size() == 0) {
                    return builder.build();
                }
                Map<String, String> firstInfo = energyEfficiencyRatio.get(0);
                String lastStartTime = firstInfo.get("end_time");
                String lastStart = lastStartTime.substring(0, lastStartTime.indexOf("."));
                double result = eerCalculation(lastStart, endTime);
                build.addEnergyEfficiencyRatioInfo(EnergyEfficiencyRatioInfo.newBuilder().setEnergyEfficiencyRatio(result).setStartTime(lastStart).setEndTime(endTime).build());

                for(int i = 0; i < energyEfficiencyRatio.size(); i++) {
                    Map<String, String> map = energyEfficiencyRatio.get(i);
                    String energy_efficiency_ratio = map.get("energy_efficiency_ratio");
                    String sTime = map.get("start_time");
                    String start_time = sTime.substring(0, sTime.indexOf("."));
                    String eTime = map.get("end_time");
                    String end_time = eTime.substring(0, eTime.indexOf("."));
                    build.addEnergyEfficiencyRatioInfo(EnergyEfficiencyRatioInfo.newBuilder().setEnergyEfficiencyRatio(Double.valueOf(energy_efficiency_ratio)).setStartTime(start_time).setEndTime(end_time).build());
                }
                break;
            case "day":
                String lastStartDay = CalendarUtil.getTimesmorning();
                double resultDay = eerCalculation(lastStartDay, endTime);
                build.addEnergyEfficiencyRatioInfo(EnergyEfficiencyRatioInfo.newBuilder().setEnergyEfficiencyRatio(resultDay).setStartTime(lastStartDay).setEndTime(endTime).build());
                List<Map<String, String>> energyEfficiencyRatioDay = energyViewProviderDao.findEnergyEfficiencyRatioByCycle(cycle);
                if(energyEfficiencyRatioDay == null || energyEfficiencyRatioDay.size() == 0) {
                    return builder.build();
                }
                for(int i = 0; i < energyEfficiencyRatioDay.size(); i++) {
                    Map<String, String> map = energyEfficiencyRatioDay.get(i);
                    String energy_efficiency_ratio = map.get("energy_efficiency_ratio");
                    String sTime = map.get("start_time");
                    String start_time = sTime.substring(0, sTime.indexOf("."));
                    String eTime = map.get("end_time");
                    String end_time = eTime.substring(0, eTime.indexOf("."));
                    build.addEnergyEfficiencyRatioInfo(EnergyEfficiencyRatioInfo.newBuilder().setEnergyEfficiencyRatio(Double.valueOf(energy_efficiency_ratio)).setStartTime(start_time).setEndTime(end_time).build());
                }
                break;
            case "week":
                String lastStartWeek = calendarUtil.getMondayOFWeek();
                if(lastStartWeek.length() == 10) {
                    lastStartWeek += " 00:00:00";
                }
                double resultWeek = eerCalculation(lastStartWeek, endTime);
                build.addEnergyEfficiencyRatioInfo(EnergyEfficiencyRatioInfo.newBuilder().setEnergyEfficiencyRatio(resultWeek).setStartTime(lastStartWeek).setEndTime(endTime).build());
                List<Map<String, String>> energyEfficiencyRatioWeek = energyViewProviderDao.findEnergyEfficiencyRatioByCycle(cycle);
                if(energyEfficiencyRatioWeek == null || energyEfficiencyRatioWeek.size() == 0) {
                    return builder.build();
                }
                for(int i = 0; i < energyEfficiencyRatioWeek.size(); i++) {
                    Map<String, String> map = energyEfficiencyRatioWeek.get(i);
                    String energy_efficiency_ratio = map.get("energy_efficiency_ratio");
                    String sTime = map.get("start_time");
                    String start_time = sTime.substring(0, sTime.indexOf("."));
                    String eTime = map.get("end_time");
                    String end_time = eTime.substring(0, eTime.indexOf("."));
                    build.addEnergyEfficiencyRatioInfo(EnergyEfficiencyRatioInfo.newBuilder().setEnergyEfficiencyRatio(Double.valueOf(energy_efficiency_ratio)).setStartTime(start_time).setEndTime(end_time).build());
                }
                break;
            case "month":
                String firstDayOfMonth = calendarUtil.getFirstDayOfMonth();
                if(firstDayOfMonth.length() == 10) {
                    firstDayOfMonth += " 00:00:00";
                }
                double resultMonth = 0;
                Map<String, String> day = energyViewProviderDao.findAvgEer(firstDayOfMonth, endTime, "day");
                if (null == day || day.size() == 0) {
                    resultMonth = 0;
                } else {
                    String avg = day.get("avg");
                    if (StringUtil.isEmpty(avg)) {
                        resultMonth = 0;
                    } else {
                        BigDecimal bigDecimal = new BigDecimal(avg).setScale(2,BigDecimal.ROUND_HALF_UP);
                        resultMonth = bigDecimal.doubleValue();
                    }
                }
                build.addEnergyEfficiencyRatioInfo(EnergyEfficiencyRatioInfo.newBuilder().setEnergyEfficiencyRatio(resultMonth).setStartTime(firstDayOfMonth).setEndTime(endTime).build());
                List<Map<String, String>> energyEfficiencyRatioMonth = energyViewProviderDao.findEnergyEfficiencyRatioByCycle(cycle);
                if(energyEfficiencyRatioMonth == null || energyEfficiencyRatioMonth.size() == 0) {
                    return builder.build();
                }
                for(int i = 0; i < energyEfficiencyRatioMonth.size(); i++) {
                    Map<String, String> map = energyEfficiencyRatioMonth.get(i);
                    String energy_efficiency_ratio = map.get("energy_efficiency_ratio");
                    String start_time=TimeConvertUtil.mysqlTimeSubstring(map.get("start_time"));
                    String end_time=TimeConvertUtil.mysqlTimeSubstring(map.get("end_time"));
                    build.addEnergyEfficiencyRatioInfo(EnergyEfficiencyRatioInfo.newBuilder().setEnergyEfficiencyRatio(Double.valueOf(energy_efficiency_ratio)).setStartTime(start_time).setEndTime(end_time).build());
                }

                break;
            case "year":
                break;
            default:
                return builder.build();
        }
        return builder.setData(build).build();
    }

    @Override
    public GetBusinessServersReply getBusinessServers(String businessId, String str) {
        GetBusinessServersReply.Builder builder = GetBusinessServersReply.newBuilder();
        BusinessServersData.Builder build = BusinessServersData.newBuilder();
        //遍历数组，通过http调用market业务接口查询业务下所含设备sn
        JSONObject json = HttpUtil.getHttpsRequest(url +businessId + "?token=market_token" );
        JSONObject data = json.getJSONObject("data");
        JSONObject business = data.getJSONObject("business");
        JSONArray businessDeviceInfos = business.getJSONArray("businessDeviceInfos");
        if(businessDeviceInfos.length() == 0 || null == businessDeviceInfos) {
            return builder.build();
        }
        if(StringUtil.isEmpty(str)){
            for(int j = 0; j < businessDeviceInfos.length(); j++) {
                String equipmentNumber = businessDeviceInfos.getJSONObject(j).get("equipmentNumber").toString();
                String type = businessDeviceInfos.getJSONObject(j).get("type").toString();
                Map<String, String> map = energyViewProviderDao.findIpBySn(equipmentNumber);
                if (null == map || map.size() == 0) {
                    continue;
                }
                String ip = map.get("ip");
                Map<String, String> strategyIdBySn = energyViewProviderDao.findStrategyIdBySn(equipmentNumber);
                if(null == strategyIdBySn || strategyIdBySn.size() == 0) {
                    build.addBusinessServerList(BusinessServer.newBuilder().setDeviceId(equipmentNumber).setIp(ip).setType(type).build());
                    continue;
                }else {
                    String strategyID = strategyIdBySn.get("strategyID");
                    Map<String, String> strategyMap = energyViewProviderDao.findStrategyNameById(strategyID);
                    String strategy=strategyMap.get("strategyName");
                    build.addBusinessServerList(BusinessServer.newBuilder().setDeviceId(equipmentNumber).setIp(ip).setStrategy(strategy).setStrategyId(strategyID).setType(type).build());
                }
            }
        }else {
            for(int j=0;j<businessDeviceInfos.length();j++){
                String equipmentNumber = businessDeviceInfos.getJSONObject(j).get("equipmentNumber").toString();
                if(!equipmentNumber.contains(str)){
                    continue;
                }
                String type = businessDeviceInfos.getJSONObject(j).get("type").toString();
                Map<String, String> map = energyViewProviderDao.findIpBySn(equipmentNumber);
                String ip = map.get("ip");
                Map<String, String> strategyIdBySn = energyViewProviderDao.findStrategyIdBySn(equipmentNumber);
                if(null == strategyIdBySn || strategyIdBySn.size() == 0){
                    build.addBusinessServerList(BusinessServer.newBuilder().setDeviceId(equipmentNumber).setIp(ip).setType(type).build());
                    continue;
                }else {
                    String strategyID = strategyIdBySn.get("strategyID");
                    Map<String, String> strategyMap = energyViewProviderDao.findStrategyNameById(strategyID);
                    String strategy=strategyMap.get("strategyName");
                    build.addBusinessServerList(BusinessServer.newBuilder().setDeviceId(equipmentNumber).setIp(ip).setStrategy(strategy).setStrategyId(strategyID).setType(type).build());
                }
            }

        }
        return builder.setData(build).build();
    }

    //计算能效比函数
    private double eerCalculation(String start_time,String end_time){
        Map<String, String> avgQps = energyViewProviderDao.findAvgQps(start_time, end_time);
        if(avgQps == null || avgQps.size() == 0) {
            return 0;
        }
        Double qpsAvg = Double.valueOf(avgQps.get("avg"));
        if(qpsAvg == 0){
            return 0;
        }
        List<BigDecimal> list = new ArrayList<>();
        BigDecimal bigDecimal = new BigDecimal(qpsAvg);
        //获取所有服务器历史功耗
        List<PowerByLabel> allServer = powerDataService.getPowerForAi("AllServer", start_time, end_time, 0).getDataList();
        if (null == allServer || allServer.size() == 0) {
            return 0;
        }
        //获取所有服务器总功耗列表
        List<PowerInfo> infosList = allServer.get(0).getInfosList();
        for(int i=0;i<infosList.size();i++){
            int sumSerPower = infosList.get(i).getSumSerPower();
            list.add(new BigDecimal(sumSerPower));
        }
        double avg = getAvg(list);
        if(avg==0){
            return 0;
        }
        BigDecimal multiply = bigDecimal.divide(new BigDecimal(avg), 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));
        double result = multiply.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
        return result;
    }

    private double getAvg(List<BigDecimal> list) {
        if (null == list || list.isEmpty() || list.size() == 0) {
            return 0;
        }
        BigDecimal sum = new BigDecimal(0);
        for (int i = 0; i < list.size(); i++) {
            sum = sum.add(list.get(i));
        }
        double b = sum.divide(new BigDecimal(list.size()), 2, BigDecimal.ROUND_HALF_UP).doubleValue();
        return b;
    }
}
